package com.hmall.search.controller;


import cn.hutool.core.util.StrUtil;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.api.dto.ItemDTO;
import com.hmall.common.domain.PageDTO;
import com.hmall.common.domain.PageQuery;
import com.hmall.search.domain.po.Item;
import com.hmall.search.domain.query.ItemPageQuery;
import com.hmall.search.service.ISearchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "搜索相关接口")
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
@Slf4j
public class SearchController {

    private final ISearchService searchService;


    /**
     * 搜索商品
     * @param query
     * @return
     */
    @ApiOperation("搜索商品")
    @GetMapping("/list")
    public PageDTO<ItemDTO> search(ItemPageQuery query) throws IOException {
        log.info("使用es进行搜索商品，{}",query);
//        // 分页查询
//        Page<Item> result = itemService.lambdaQuery()
//                .like(StrUtil.isNotBlank(query.getKey()), Item::getName, query.getKey())
//                .eq(StrUtil.isNotBlank(query.getBrand()), Item::getBrand, query.getBrand())
//                .eq(StrUtil.isNotBlank(query.getCategory()), Item::getCategory, query.getCategory())
//                .eq(Item::getStatus, 1)
//                .between(query.getMaxPrice() != null, Item::getPrice, query.getMinPrice(), query.getMaxPrice())
//                .page(query.toMpPage("update_time", false));
        // 封装并返回
      return searchService.itemPageQuery(query);

    }

    /**
     * 使用es在索引库items中根据id搜索商品
     * @param id
     * @return
     */
    @ApiOperation("根据id搜索商品")
    @GetMapping("/{id}")
   public ItemDTO searchById(@PathVariable("id") Long id ) throws IOException {
        return searchService.searchById(id);
    }

    /**
     * 搜索商品，过滤
     * @param query
     * @return
     */
    @ApiOperation("搜索商品分类")
    @PostMapping("/filters")
    public  Map<String, List<String>> filters(ItemPageQuery query) throws IOException {
        log.info("开始搜索商品分类");
         return searchService.filters(query);
    }
}
